package com.myproject.service.impl;

import com.myproject.dto.LoginRequestDTO;
import com.myproject.dto.LoginResponseDTO;
import com.myproject.dto.UserInfoDTO;
import com.myproject.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

//	@Autowired
//	private AuthenticationManager authenticationManager;

	private static final String CAPTCHA_PREFIX = "captcha:";
	private static final String TOKEN_PREFIX = "token:";

    private final AuthenticationManager authenticationManager;
    
    // 改用构造器注入（避免字段注入循环问题）
    @Autowired
    public AuthServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    
	@Override
	public LoginResponseDTO login(LoginRequestDTO request) {
		// 1. 验证验证码
		validateCaptcha(request.getCaptchaKey(), request.getCaptchaCode());

		// 2. 验证用户凭证
		Authentication authentication = authenticationManager
				.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));

		// 3. 生成访问令牌
		String accessToken = generateToken(authentication.getName());

		// 4. 构建响应
		LoginResponseDTO response = new LoginResponseDTO();
		response.setAccessToken(accessToken);
		response.setExpiresIn(3600L); // 1小时过期

		// 设置用户信息
		UserInfoDTO userInfo = new UserInfoDTO();
		userInfo.setUsername(authentication.getName());
		// 这里可以设置更多用户信息
		response.setUserInfo(userInfo);

		return response;
	}

	private void validateCaptcha(String captchaKey, String captchaCode) {
		String key = CAPTCHA_PREFIX + captchaKey;
		String storedCode = redisTemplate.opsForValue().get(key);

		if (storedCode == null) {
			throw new RuntimeException("验证码已过期");
		}

		if (!storedCode.equalsIgnoreCase(captchaCode)) {
			throw new RuntimeException("验证码错误");
		}

		// 验证成功后删除验证码
		redisTemplate.delete(key);
	}

	private String generateToken(String username) {
		String token = UUID.randomUUID().toString();
		redisTemplate.opsForValue().set(TOKEN_PREFIX + token, username, 1, TimeUnit.HOURS);
		return token;
	}
}